# employee_list_widget.py
import os
import sys
import time

import cv2
import face_recognition
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap, QIcon
from PyQt5.QtWidgets import (QWidget, QPushButton, QTableWidget,
                             QTableWidgetItem, QHeaderView, QAbstractItemView, QLabel,
                             QHBoxLayout, QGroupBox, QLineEdit, QFileDialog, QMessageBox,
                             QVBoxLayout, QMainWindow, QApplication)

from db import EmployeeDB  # 导入数据库操作类


class EmployeeListWidget(QWidget):
    def __init__(self, main_window, parent=None):
        super(EmployeeListWidget, self).__init__(parent)
        self.main_window = main_window  # 保存对主窗口的引用
        self.setup_ui()

        # 初始化数据库
        self.db = EmployeeDB()

        # 加载员工数据
        self.load_employees()

        # 分页相关变量
        self.current_page = 1
        self.items_per_page = 10

        # 当前选择的头像数据
        self.current_avatar_path = None
        self.current_face_encoding = None  # 当前人脸特征向量

        # 填充员工列表
        self.update_pagination()
        self.populate_employee_list()

    def load_employees(self):
        """从数据库加载员工数据（包含人脸特征）"""
        self.employees = self.db.get_all_employees()

    def setup_ui(self):
        # 主布局
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(0, 0, 0, 0)
        main_layout.setSpacing(15)

        # 返回和添加员工
        self._layout_top_btn(main_layout)
        # 员工列表表格
        self._layout_employee_table(main_layout)
        # 分页控件
        self._layout_pagination(main_layout)
        # 员工信息录入表单
        self._layout_employee_info_form(main_layout)

        # 连接信号
        self.add_btn.clicked.connect(self.add_employee)
        self.prev_page_btn.clicked.connect(self.prev_page)
        self.next_page_btn.clicked.connect(self.next_page)
        self.select_photo_btn.clicked.connect(self.select_photo)
        self.capture_photo_btn.clicked.connect(self.capture_photo)
        self.submit_btn.clicked.connect(self.submit_employee)

    def _layout_pagination(self, main_layout):
        # 分页控件
        pagination_container = QWidget()
        pagination_layout = QHBoxLayout(pagination_container)
        pagination_layout.setContentsMargins(0, 10, 0, 0)
        pagination_layout.setSpacing(10)
        pagination_layout.addStretch(1)
        # 上一页按钮
        self.prev_page_btn = QPushButton("上一页")
        self.prev_page_btn.setObjectName("prev_page_btn")
        self.prev_page_btn.setStyleSheet("""
                QPushButton#prev_page_btn {
                    background-color: rgba(36, 183, 231, 0.3);
                    color: white;
                    font: bold 12pt "微软雅黑";
                    padding: 6px 12px;
                    border-radius: 6px;
                    border: 1px solid #24b7e7;
                }
                QPushButton#prev_page_btn:hover {
                    background-color: rgba(36, 183, 231, 0.5);
                }
                QPushButton#prev_page_btn:pressed {
                    background-color: rgba(36, 183, 231, 0.7);
                }
            """)
        pagination_layout.addWidget(self.prev_page_btn)
        # 页码标签
        self.page_label = QLabel("第1页")
        self.page_label.setObjectName("page_label")
        self.page_label.setStyleSheet("""
                QLabel#page_label {
                    font: 12pt "微软雅黑";
                    color: white;
                }
            """)
        pagination_layout.addWidget(self.page_label)
        # 下一页按钮
        self.next_page_btn = QPushButton("下一页")
        self.next_page_btn.setObjectName("next_page_btn")
        self.next_page_btn.setStyleSheet("""
                QPushButton#next_page_btn {
                    background-color: rgba(36, 183, 231, 0.3);
                    color: white;
                    font: bold 12pt "微软雅黑";
                    padding: 6px 12px;
                    border-radius: 6px;
                    border: 1px solid #24b7e7;
                }
                QPushButton#next_page_btn:hover {
                    background-color: rgba(36, 183, 231, 0.5);
                }
                QPushButton#next_page_btn:pressed {
                    background-color: rgba(36, 183, 231, 0.7);
                }
            """)
        pagination_layout.addWidget(self.next_page_btn)
        # 添加弹簧使分页控件居中
        pagination_layout.addStretch(1)
        main_layout.addWidget(pagination_container)

    def _layout_top_btn(self, main_layout):
        # 按钮容器
        button_container = QWidget()
        button_layout = QHBoxLayout(button_container)
        button_layout.setContentsMargins(0, 0, 0, 0)
        button_layout.setSpacing(20)
        # 返回按钮
        self.back_btn = QPushButton("返回")
        self.back_btn.setObjectName("back_btn")
        self.back_btn.setStyleSheet("""
                QPushButton#back_btn {
                    background-color: rgba(92, 225, 182, 0.3);
                    color: white;
                    font: bold 16pt "微软雅黑";
                    padding: 8px 16px;
                    border-radius: 8px;
                    border: 1px solid #5ce1b6;
                }
                QPushButton#back_btn:hover {
                    background-color: rgba(92, 225, 182, 0.5);
                }
                QPushButton#back_btn:pressed {
                    background-color: rgba(92, 225, 182, 0.7);
                }
            """)
        button_layout.addWidget(self.back_btn)
        # 添加员工按钮
        self.add_btn = QPushButton("添加员工")
        self.add_btn.setObjectName("add_btn")
        self.add_btn.setStyleSheet("""
                QPushButton#add_btn {
                    background-color: rgba(36, 183, 231, 0.3);
                    color: white;
                    font: bold 16pt "微软雅黑";
                    padding: 8px 16px;
                    border-radius: 8px;
                    border: 1px solid #24b7e7;
                }
                QPushButton#add_btn:hover {
                    background-color: rgba(36, 183, 231, 0.5);
                }
                QPushButton#add_btn:pressed {
                    background-color: rgba(36, 183, 231, 0.7);
                }
            """)
        button_layout.addWidget(self.add_btn)
        main_layout.addWidget(button_container)

    def _layout_employee_table(self, main_layout):
        self.employee_table = QTableWidget()
        self.employee_table.setObjectName("employee_table")

        # gridline-color 网格线
        self.employee_table.setStyleSheet("""
                QTableWidget#employee_table {
                    background-color: rgba(20, 40, 60, 0.6);
                    border: 1px solid #3a506b;
                    border-radius: 8px;
                    color: white;
                    gridline-color: #3a506b;
                    font: 14pt "微软雅黑";
                }
                QHeaderView::section {
                    background-color: rgba(92, 225, 182, 1);
                    color: white;
                    padding: 5px;
                    font: bold 16pt "微软雅黑";
                    border: none;
                    border-bottom: 2px solid #3a506b;
                }
            """)
        # 5列
        self.employee_table.setColumnCount(5)
        self.employee_table.setHorizontalHeaderLabels(["序号", "姓名", "工号", "头像", "操作"])
        self.employee_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.employee_table.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeToContents)
        self.employee_table.horizontalHeader().setSectionResizeMode(3, QHeaderView.ResizeToContents)
        self.employee_table.horizontalHeader().setSectionResizeMode(4, QHeaderView.ResizeToContents)
        self.employee_table.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.employee_table.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.employee_table.setSelectionMode(QAbstractItemView.SingleSelection)
        self.employee_table.verticalHeader().setVisible(False)
        main_layout.addWidget(self.employee_table)

    def _layout_employee_info_form(self, layout):
        """创建员工信息录入表单"""
        # 表单容器
        form_group = QGroupBox("员工信息录入")
        form_group.setStyleSheet("""
                QGroupBox {
                    background-color: rgba(40, 50, 80, 0.7);
                    border: 1px solid #24b7e;
                    border-radius: 10px;
                    font: bold 18pt "微软雅黑";
                    color: #24b7e7;
                    margin-top: 25px;
                    padding-top: 25px;
                }
            """)
        form_layout = QVBoxLayout(form_group)
        form_layout.setContentsMargins(15, 15, 15, 15)
        form_layout.setSpacing(15)

        # 姓名输入框
        name_layout = QHBoxLayout()
        name_label = QLabel("姓名:")
        name_label.setStyleSheet("font: 16pt '微软雅黑'; color: white; min-width: 80px;")
        self.name_input = QLineEdit()
        self.name_input.setPlaceholderText("输入员工姓名")
        self.name_input.setStyleSheet("""
                QLineEdit {
                    font: 16pt "微软雅黑";
                    padding: 10px;
                    border: 2px solid #24b7e7;
                    border-radius: 8px;
                    background-color: rgba(20, 40, 60, 0.6);
                    color: white;
                }
            """)
        name_layout.addWidget(name_label)
        name_layout.addWidget(self.name_input)
        form_layout.addLayout(name_layout)

        # 工号输入框
        id_layout = QHBoxLayout()
        id_label = QLabel("工号:")
        id_label.setStyleSheet("font: 16pt '微软雅黑'; color: white; min-width: 80px;")
        self.id_input = QLineEdit()
        self.id_input.setPlaceholderText("输入员工工号")
        self.id_input.setStyleSheet("""
                QLineEdit {
                    font: 16pt "微软雅黑";
                    padding: 10px;
                    border: 2px solid #24b7e7;
                    border-radius: 8px;
                    background-color: rgba(20, 40, 60, 0.6);
                    color: white;
                }
            """)
        id_layout.addWidget(id_label)
        id_layout.addWidget(self.id_input)
        form_layout.addLayout(id_layout)

        # 头像选择区域
        avatar_layout = QHBoxLayout()
        avatar_label = QLabel("头像:")
        avatar_label.setStyleSheet("font: 16pt '微软雅黑'; color: white; min-width: 80px;")

        # 头像容器
        self.avatar_preview = QLabel()
        self.avatar_preview.setFixedSize(120, 120)
        self.avatar_preview.setStyleSheet("""
                QLabel {
                    background-color: rgba(20, 40, 60, 0.8);
                    border: 2px dashed #24b7e7;
                    border-radius: 5px;
                }
            """)
        self.avatar_preview.setAlignment(Qt.AlignCenter)
        self.avatar_preview.setText("无头像")

        # 按钮容器
        avatar_btn_layout = QVBoxLayout()
        avatar_btn_layout.setSpacing(10)

        # 选择照片按钮
        self.select_photo_btn = QPushButton("选择照片")
        self.select_photo_btn.setStyleSheet("""
                QPushButton {
                    background-color: rgba(92, 225, 182, 0.3);
                    color: white;
                    font: bold 12pt "微软雅黑";
                    padding: 8px 12px;
                    border-radius: 6px;
                    border: 1px solid #5ce1b6;
                }
                QPushButton:hover {
                    background-color: rgba(92, 225, 182, 0.5);
                }
                QPushButton:pressed {
                    background-color: rgba(92, 225, 182, 0.7);
                }
            """)
        avatar_btn_layout.addWidget(self.select_photo_btn)

        # 拍照按钮
        self.capture_photo_btn = QPushButton("拍照")
        self.capture_photo_btn.setStyleSheet("""
                QPushButton {
                    background-color: rgba(36, 183, 231, 0.3);
                    color: white;
                    font: bold 12pt "微软雅黑";
                    padding: 8px 12px;
                    border-radius: 6px;
                    border: 1px solid #24b7e7;
                }
                QPushButton:hover {
                    background-color: rgba(36, 183, 231, 0.5);
                }
                QPushButton:pressed {
                    background-color: rgba(36, 183, 231, 0.7);
                }
            """)
        avatar_btn_layout.addWidget(self.capture_photo_btn)

        avatar_layout.addWidget(avatar_label)
        avatar_layout.addWidget(self.avatar_preview)
        avatar_layout.addLayout(avatar_btn_layout)
        form_layout.addLayout(avatar_layout)

        # 提交按钮
        self.submit_btn = QPushButton("提交")
        self.submit_btn.setStyleSheet("""
                QPushButton {
                    background-color: rgba(92, 225, 182, 0.3);
                    color: white;
                    font: bold 16pt "微软雅黑";
                    padding: 10px 20px;
                    border-radius: 10px;
                    border: 2px solid #5ce1b6;
                }
                QPushButton:hover {
                    background-color: rgba(92, 225, 182, 0.5);
                }
                QPushButton:pressed {
                    background-color: rgba(92, 225, 182, 0.7);
                }
            """)
        form_layout.addWidget(self.submit_btn)

        layout.addWidget(form_group)

    def add_employee(self):
        """清空表单，准备添加新员工"""
        # 清空表单
        self.name_input.clear()
        self.id_input.clear()
        self.avatar_preview.clear()
        self.avatar_preview.setText("无头像")
        self.current_avatar_path = None
        self.current_face_encoding = None  # 清空人脸特征

        # 确保提交按钮显示"提交"
        self.submit_btn.setText("提交")

        # 移除任何编辑状态
        if hasattr(self, 'editing_row'):
            delattr(self, 'editing_row')

        # 将焦点设置到姓名输入框
        self.name_input.setFocus()

    def capture_photo(self):
        """使用主窗口的摄像头直接拍照并提取人脸特征"""
        # 检查主窗口是否有摄像头
        if not hasattr(self.main_window, 'video_capture') or not self.main_window.video_capture.isOpened():
            QMessageBox.warning(self, "摄像头错误", "主摄像头未就绪！", QMessageBox.Ok)
            return

        # 从主窗口获取当前帧
        if not hasattr(self.main_window, 'current_frame') or self.main_window.current_frame is None:
            QMessageBox.warning(self, "拍照失败", "无法获取当前摄像头画面", QMessageBox.Ok)
            return

        # 保存照片
        timestamp = time.strftime("%Y%m%d_%H%M%S")
        avatar_dir = "avatars"
        os.makedirs(avatar_dir, exist_ok=True)
        avatar_path = os.path.join(avatar_dir, f"avatar_{timestamp}.jpg")
        cv2.imwrite(avatar_path, self.main_window.current_frame)

        # 提取人脸特征
        success, face_encoding = self._extract_face_encoding(avatar_path)
        if not success:
            QMessageBox.warning(self, "人脸检测失败", "未检测到人脸，请确保面部清晰可见！", QMessageBox.Ok)
            return

        # 设置当前头像和人脸特征
        self.current_avatar_path = avatar_path
        self.current_face_encoding = face_encoding

        # 在预览区域显示
        pixmap = QPixmap(avatar_path)
        if not pixmap.isNull():
            scaled = pixmap.scaled(120, 120, Qt.KeepAspectRatio, Qt.SmoothTransformation)
            self.avatar_preview.setPixmap(scaled)
            self.avatar_preview.setText("")

        QMessageBox.information(self, "拍照成功", "员工照片已拍摄并设置为头像！", QMessageBox.Ok)

    def _extract_face_encoding(self, image_path):
        """从图片中提取人脸特征向量"""
        try:
            # 加载图片
            image = face_recognition.load_image_file(image_path)

            # 检测人脸位置
            face_locations = face_recognition.face_locations(image)

            if not face_locations:
                return False, None

            # 提取人脸特征
            face_encodings = face_recognition.face_encodings(image, face_locations)

            if not face_encodings:
                return False, None

            # 取第一个人脸特征
            return True, face_encodings[0].tobytes()
        except Exception as e:
            print(f"提取人脸特征时出错: {e}")
            return False, None

    def select_photo(self):
        """选择本地照片作为头像并提取人脸特征"""
        options = QFileDialog.Options()
        file_name, _ = QFileDialog.getOpenFileName(
            self, "选择头像", "",
            "图片文件 (*.jpg *.jpeg *.png *.bmp)",
            options=options
        )

        if file_name:
            # 提取人脸特征
            success, face_encoding = self._extract_face_encoding(file_name)
            if not success:
                QMessageBox.warning(self, "人脸检测失败", "未检测到人脸，请选择包含清晰面部的照片！", QMessageBox.Ok)
                return

            self.current_avatar_path = file_name
            self.current_face_encoding = face_encoding

            # 预览头像
            pixmap = QPixmap(file_name)
            if not pixmap.isNull():
                scaled = pixmap.scaled(120, 120, Qt.KeepAspectRatio, Qt.SmoothTransformation)
                self.avatar_preview.setPixmap(scaled)
                self.avatar_preview.setText("")

    def update_pagination(self):
        """更新分页控件状态"""
        total_pages = (len(self.employees) + self.items_per_page - 1) // self.items_per_page
        self.page_label.setText(f"第{self.current_page}页/共{total_pages}页")

        # 更新按钮状态
        self.prev_page_btn.setEnabled(self.current_page > 1)
        self.next_page_btn.setEnabled(self.current_page < total_pages)

    def prev_page(self):
        """上一页"""
        if self.current_page > 1:
            self.current_page -= 1
            self.populate_employee_list()

    def next_page(self):
        """下一页"""
        total_pages = (len(self.employees) + self.items_per_page - 1) // self.items_per_page
        if self.current_page < total_pages:
            self.current_page += 1
            self.populate_employee_list()

    def populate_employee_list(self):
        """填充员工列表（带分页）"""
        # 计算当前页的开始和结束索引
        start_index = (self.current_page - 1) * self.items_per_page
        end_index = min(start_index + self.items_per_page, len(self.employees))

        # 更新分页控件
        self.update_pagination()

        # 设置表格行数
        self.employee_table.setRowCount(end_index - start_index)

        for row in range(start_index, end_index):
            employee = self.employees[row]
            display_row = row - start_index

            # 序号
            self.employee_table.setItem(display_row, 0, QTableWidgetItem(str(row + 1)))

            # 姓名
            self.employee_table.setItem(display_row, 1, QTableWidgetItem(employee["name"]))

            # 工号
            self.employee_table.setItem(display_row, 2, QTableWidgetItem(employee["employee_id"]))

            # 头像
            avatar_label = QLabel()
            avatar_label.setAlignment(Qt.AlignCenter)

            if os.path.exists(employee["avatar"]):
                pixmap = QPixmap(employee["avatar"])
                if not pixmap.isNull():
                    # 创建缩略图
                    scaled = pixmap.scaled(60, 60, Qt.KeepAspectRatio, Qt.SmoothTransformation)
                    avatar_label.setPixmap(scaled)
            else:
                # 使用默认头像图标
                avatar_label.setText("👤")
                avatar_label.setStyleSheet("font-size: 24pt;")

            self.employee_table.setCellWidget(display_row, 3, avatar_label)

            # 操作按钮
            btn_frame = QWidget()
            btn_layout = QHBoxLayout(btn_frame)
            btn_layout.setContentsMargins(0, 0, 0, 0)
            btn_layout.setSpacing(5)

            # 编辑按钮
            edit_btn = QPushButton("编辑")
            edit_btn.setObjectName("edit_btn")
            edit_btn.setStyleSheet("""
                    QPushButton#edit_btn {
                        background-color: rgba(92, 225, 182, 0.3);
                        color: white;
                        font: 12pt "微软雅黑";
                        padding: 5px 10px;
                        border-radius: 5px;
                        border: 1px solid #5ce1b6;
                    }
                    QPushButton#edit_btn:hover {
                        background-color: rgba(92, 225, 182, 0.5);
                    }
                    QPushButton#edit_btn:pressed {
                        background-color: rgba(92, 225, 182, 0.7);
                    }
                """)
            # 当需要在槽函数中传递额外的参数时，我们使用Lambda表达式
            # lambda [参数] : [函数体]
            # lambda 参数1, 参数2=值 : 表达式
            # 第一个参数 _ 忽略信号传递的默认参数：在PyQt中，clicked信号在触发时会自动传递一个布尔值（表示按钮的按下状态）
            # 下划线表示"这个参数存在但我不关心其内容"
            # 第二个参数，捕获当前行索引：保存按钮创建时的row值，将循环变量row的当前值绑定到参数r
            edit_btn.clicked.connect(lambda _, r=row: self.edit_employee(r))
            btn_layout.addWidget(edit_btn)

            # 删除按钮
            delete_btn = QPushButton("删除")
            delete_btn.setObjectName("delete_btn")
            delete_btn.setStyleSheet("""
                    QPushButton#delete_btn {
                        background-color: rgba(255, 100, 100, 0.3);
                        color: white;
                        font: 12pt "微软雅黑";
                        padding: 5px 10px;
                        border-radius: 5px;
                        border: 1px solid #ff6464;
                    }
                    QPushButton#delete_btn:hover {
                        background-color: rgba(255, 100, 100, 0.5);
                    }
                    QPushButton#delete_btn:pressed {
                        background-color: rgba(255, 100, 100, 0.7);
                    }
                """)
            delete_btn.clicked.connect(lambda _, r=row: self.delete_employee(r))
            btn_layout.addWidget(delete_btn)

            self.employee_table.setCellWidget(display_row, 4, btn_frame)

    def submit_employee(self):
        """提交员工信息（包含人脸特征）"""
        name = self.name_input.text().strip()
        employee_id = self.id_input.text().strip()

        if not name:
            QMessageBox.warning(self, "输入错误", "请输入员工姓名！", QMessageBox.Ok)
            self.name_input.setFocus()
            return

        if not employee_id:
            QMessageBox.warning(self, "输入错误", "请输入员工工号！", QMessageBox.Ok)
            self.id_input.setFocus()
            return

        if not self.current_avatar_path:
            QMessageBox.warning(self, "选择错误", "请选择员工头像！", QMessageBox.Ok)
            return

        # 检查人脸特征是否存在
        if self.current_face_encoding is None:
            QMessageBox.warning(self, "人脸识别错误", "无法提取人脸特征，请重新拍照或选择照片！", QMessageBox.Ok)
            return

        # 检查工号是否已存在
        existing_employee = self.db.get_employee_by_id(employee_id)

        if self.current_avatar_path:
            # 如果是新选择的头像（非拍照创建）
            if not self.current_avatar_path.startswith("avatars"):
                # 复制文件到avatars目录
                avatar_dir = "avatars"
                os.makedirs(avatar_dir, exist_ok=True)
                timestamp = time.strftime("%Y%m%d_%H%M%S")
                file_ext = os.path.splitext(self.current_avatar_path)[1]
                new_avatar_name = f"avatar_{timestamp}{file_ext}"
                new_avatar_path = os.path.join(avatar_dir, new_avatar_name)

                try:
                    # 复制文件
                    import shutil
                    shutil.copy2(self.current_avatar_path, new_avatar_path)
                    self.current_avatar_path = new_avatar_path
                except Exception as e:
                    QMessageBox.warning(self, "文件复制失败", f"无法复制头像文件: {str(e)}", QMessageBox.Ok)
                    return

        # 如果是编辑模式
        if hasattr(self, 'editing_row') and self.submit_btn.text() == "更新":
            if existing_employee and existing_employee["employee_id"] != employee_id:
                QMessageBox.warning(self, "工号冲突", "该工号已被其他员工使用！", QMessageBox.Ok)
                return

            # 更新员工信息
            if 0 <= self.editing_row < len(self.employees):
                old_employee = self.employees[self.editing_row]
                if self.db.update_employee(
                        old_employee["employee_id"],
                        name,
                        self.current_avatar_path,
                        self.current_face_encoding
                ):
                    QMessageBox.information(self, "更新成功", f"员工 {name} 信息已更新！", QMessageBox.Ok)

                    # 删除旧的头像文件（如果有）
                    if hasattr(self, 'old_avatar_path') and self.old_avatar_path:
                        self.delete_avatar_file(self.old_avatar_path)

                    # 重新加载数据并刷新表格
                    self.load_employees()
                    self.populate_employee_list()

                    # 重置编辑状态
                    self.submit_btn.setText("提交")
                    delattr(self, 'editing_row')

                    # 清空表单
                    self.name_input.clear()
                    self.id_input.clear()
                    self.avatar_preview.clear()
                    self.avatar_preview.setText("无头像")
                    self.current_avatar_path = None
                    self.current_face_encoding = None

                    # 通知人脸识别数据更新
                    if hasattr(self.main_window, 'face_manager'):
                        self.main_window.face_manager.reload_face_data()
                else:
                    QMessageBox.warning(self, "更新失败", "员工信息更新失败，请重试！", QMessageBox.Ok)
            else:
                QMessageBox.warning(self, "编辑错误", "无效的编辑行！", QMessageBox.Ok)
        else:
            # 添加新员工模式
            if existing_employee:
                QMessageBox.warning(self, "添加失败", "该工号已存在！", QMessageBox.Ok)
                self.id_input.setFocus()
                return

            # 添加新员工到数据库
            if self.db.add_employee(
                    employee_id,
                    name,
                    self.current_avatar_path,
                    self.current_face_encoding
            ):
                QMessageBox.information(self, "添加成功", f"员工 {name} 已成功添加！", QMessageBox.Ok)

                # 更新员工列表
                self.load_employees()
                self.populate_employee_list()

                # 清空表单
                self.name_input.clear()
                self.id_input.clear()
                self.avatar_preview.clear()
                self.avatar_preview.setText("无头像")
                self.current_avatar_path = None
                self.current_face_encoding = None

                # 通知人脸识别数据更新
                if hasattr(self.main_window, 'face_manager'):
                    self.main_window.face_manager.reload_face_data()
            else:
                QMessageBox.warning(self, "添加失败", "员工添加失败，请重试！", QMessageBox.Ok)

    def edit_employee(self, row):
        """编辑员工信息"""
        if 0 <= row < len(self.employees):
            employee = self.employees[row]

            # 记录旧头像路径
            self.old_avatar_path = employee["avatar"]
            # 填充表单
            self.name_input.setText(employee["name"])
            self.id_input.setText(employee["employee_id"])

            # 加载人脸特征（如果存在）
            if "face_encoding" in employee and employee["face_encoding"] is not None:
                self.current_face_encoding = employee["face_encoding"]
            else:
                self.current_face_encoding = None

            # 加载头像预览
            if os.path.exists(employee["avatar"]):
                pixmap = QPixmap(employee["avatar"])
                if not pixmap.isNull():
                    # 创建缩略图
                    scaled = pixmap.scaled(120, 120, Qt.KeepAspectRatio, Qt.SmoothTransformation)
                    self.avatar_preview.setPixmap(scaled)
                    self.avatar_preview.setText("")
                    self.current_avatar_path = employee["avatar"]

            # 修改提交按钮文本
            self.submit_btn.setText("更新")

            # 临时保存当前编辑的行
            self.editing_row = row

    def delete_employee(self, row):
        """删除员工"""
        if 0 <= row < len(self.employees):
            employee = self.employees[row]
            employee_name = employee["name"]
            employee_id = employee["employee_id"]
            avatar_path = employee["avatar"]  # 获取头像路径

            reply = QMessageBox.question(
                self,
                "确认删除",
                f"确定要删除员工 {employee_name} ({employee_id}) 吗？此操作不可恢复。",
                QMessageBox.Yes | QMessageBox.No
            )

            if reply == QMessageBox.Yes:
                # 从数据库删除
                if self.db.delete_employee(employee_id):
                    # 删除头像文件
                    self.delete_avatar_file(avatar_path)

                    # 更新员工列表
                    self.load_employees()
                    self.populate_employee_list()
                    QMessageBox.information(self, "删除成功", f"员工 {employee_name} 已删除！", QMessageBox.Ok)

                    # 通知人脸识别数据更新
                    if hasattr(self.main_window, 'face_manager'):
                        self.main_window.face_manager.reload_face_data()
                else:
                    QMessageBox.warning(self, "删除失败", "删除员工失败，请重试！", QMessageBox.Ok)

    def delete_avatar_file(self, avatar_path):
        """安全删除头像文件"""
        if avatar_path and os.path.exists(avatar_path):
            try:
                # 确保只删除avatars目录下的文件，避免误删系统文件
                if os.path.abspath(avatar_path).startswith(os.path.abspath("avatars")):
                    os.remove(avatar_path)
                    print(f"已删除头像文件: {avatar_path}")
            except Exception as e:
                print(f"删除头像文件失败: {e}")

class MainWindow(QMainWindow):
    """完整的主窗口实现"""
    def __init__(self):
        super().__init__()
        self.setWindowTitle("员工管理系统")
        self.setGeometry(100, 100, 1200, 800)

        # 初始化摄像头（实际应用中需要）
        self.video_capture = None
        self.current_frame = None

        # 创建主布局
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        main_layout = QVBoxLayout(central_widget)
        main_layout.setContentsMargins(20, 20, 20, 20)

        # 添加员工列表控件
        self.employee_list = EmployeeListWidget(self)
        main_layout.addWidget(self.employee_list)

        # 连接返回按钮事件
        self.employee_list.back_btn.clicked.connect(self.close)

    def closeEvent(self, event):
        """关闭窗口时释放资源"""
        if self.video_capture and self.video_capture.isOpened():
            self.video_capture.release()
        event.accept()

if __name__ == "__main__":
    app = QApplication(sys.argv)

    # 设置应用样式
    app.setStyle("Fusion")
    palette = QtGui.QPalette()
    palette.setColor(QtGui.QPalette.Window, QtGui.QColor(10, 20, 40))
    palette.setColor(QtGui.QPalette.WindowText, QtGui.QColor(200, 220, 255))
    app.setPalette(palette)

    # 创建主窗口
    window = MainWindow()

    window.show()
    sys.exit(app.exec_())